package com.wise.service.portal.content.products;

import com.wise.entities.content.Product;
import com.wise.framework.dao.SqlSelect;
import com.wise.framework.daomodel.DaoList;
import com.wise.model.content.enums.ProductState;
import com.wise.summer.v1.portal.content.products.SearchProducts;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.summerframework.model.SummerService;
import org.summerframework.model.SummerServiceBean;

import java.util.Arrays;
import java.util.List;

/**
 * @author shaoming
 * @date 2019-09-09
 */
@Service
@SummerService
public class SearchProductsService implements SummerServiceBean<SearchProducts> {

    @Override
    public void sum(SearchProducts summer) {
        SqlSelect sqlSelect = SqlSelect.selec("*")
                .fromClassName(Product.class)
                .eq(Product._categoryType, 0)
                .eqLang(Product._lang)
                .eq(Product._state, ProductState.UP.value())
                .eq(StringUtils.isNotBlank(summer.getCategoryId()), Product._categoryId, summer.getCategoryId());
        if (StringUtils.isNotEmpty(summer.getName())) {
            //分词
            List<String> terms = Arrays.asList(org.apache.commons.lang.StringUtils.split(summer.getName(), " "));
            for (int i = 0; i < terms.size(); i++) {
                sqlSelect.like(Product._name, "%" + terms.get(i) + "%");
                if (terms.size() - i > 1) {
                    sqlSelect.or();
                }
            }
        }
        sqlSelect.order_by(Product._id);

        List<SearchProducts.Result> resultList = DaoList.s(SearchProducts.Result.class, sqlSelect);

        summer.setSummerResult(resultList);
    }
}
